package com.example.bootrocketmq;

import com.sun.org.apache.xpath.internal.operations.Or;
import org.apache.rocketmq.common.message.MessageConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Random;

/**
 * @Date 2021/9/7
 **/
@RestController
@RequestMapping("/demo")
public class DemoController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    //<1>
    @Autowired
    private CustomerChannel customerChannel;

    @GetMapping("/sendV1")
    public String send() {
        // <2>创建 Message
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setId(new Random().nextInt());
        orderMessage.setOrderName("游戏充值订单");

        // <3>创建 Spring Message 对象
        Message<OrderMessage> springMessage = MessageBuilder.withPayload(orderMessage)
                .build();
        // <4>发送消息
        boolean sendResult = customerChannel.output().send(springMessage);
        logger.info("[send][发送消息完成, 结果 = {}]", sendResult);

        return "success";
    }

    @GetMapping("/sendV2")
    public String sendTrek() {
        // <2>创建 Message
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setId(new Random().nextInt());
        orderMessage.setOrderName("游戏充值订单");

        // <3>创建 Spring Message 对象
        Message<OrderMessage> springMessage = MessageBuilder.withPayload(orderMessage)
                .setHeader("version", "2.0")
                .build();
        // <4>发送消息
        boolean sendResult = customerChannel.output().send(springMessage);
        logger.info("[sendTrek][发送消息完成, 结果 = {}]", sendResult);

        return "success";
    }

    @GetMapping("/send_delay")
    public boolean sendDelay() {
        // 创建 Message
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setId(new Random().nextInt());
        orderMessage.setOrderName("游戏充值订单-延迟消息");

        // 创建 Spring Message 对象
        Message<OrderMessage> springMessage = MessageBuilder.withPayload(orderMessage)
                .setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, "3") // 设置延迟级别为 3，10 秒后消费。
                .build();
        // 发送消息
        boolean sendResult = customerChannel.output().send(springMessage);
        logger.info("[sendDelay][发送消息完成, 结果 = {}]", sendResult);
        return sendResult;
    }

}
